<template>
  <div class="question-bank-container">
    <!-- 搜索和添加区域 -->
    <div class="search-add-section">
      <el-input
        v-model="searchId"
        placeholder="请输入题库ID进行搜索"
        class="search-input"
        clearable
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
      <el-button type="primary" @click="showCreateDialog">添加题库</el-button>
    </div>

    <!-- 题库列表 -->
    <el-table :data="questionBanks" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="题库ID" width="180" />
      <el-table-column prop="name" label="题库名称" />
      <el-table-column prop="questionCount" label="题量" width="100" />
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <div class="total-count">共 {{ total }} 条</div>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10]"
        layout="prev, pager, next, jumper"
        :total="total"
        :pager-count="5"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 创建题库对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建题库"
      width="30%"
      :close-on-click-modal="false"
      center
    >
      <div class="create-options">
        <div class="option-item" @click="goToCreateBank('template')">
          <el-icon><Files /></el-icon>
          <span>从模板创建</span>
          <p>使用预设模板快速创建题库</p>
        </div>
        <div class="option-item" @click="goToCreateBank('import')">
          <el-icon><Upload /></el-icon>
          <span>导入题库</span>
          <p>从文件导入已有题库</p>
        </div>
      </div>
    </el-dialog>

    <!-- 导入题库对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入题库"
      width="40%"
      :close-on-click-modal="false"
      center
    >
      <el-form :model="importForm" label-width="100px">
        <el-form-item label="题库名称" required>
          <el-input v-model="importForm.name" placeholder="请输入题库名称" />
        </el-form-item>
        <el-form-item label="文件上传" required>
          <el-upload
            class="upload-demo"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            accept=".xlsx,.xls,.doc,.docx"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 .xlsx、.xls、.doc、.docx 格式文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleImport" :loading="importLoading">开始导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Files, Upload, UploadFilled } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import mammoth from 'mammoth';

const router = useRouter();

// 状态变量
const searchId = ref('');
interface Bank {
  id: string;
  name: string;
  questionCount: number;
  createdAt: string;
}
const questionBanks = ref<Bank[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const createDialogVisible = ref(false);
const importDialogVisible = ref(false);
const importLoading = ref(false);

interface ImportForm {
  name: string;
  file: File | null;
}

const importForm = ref<ImportForm>({
  name: '',
  file: null
});

// 工具函数
const formatDate = (date: string): string => {
  return new Date(date).toLocaleString();
};

// 获取题库列表
const fetchQuestionBanks = async () => {
  loading.value = true;
  try {
    // 从本地存储获取题库列表
    const storedBanks = localStorage.getItem('questionBanks');
    
    if (storedBanks) {
      const parsedBanks = JSON.parse(storedBanks);
      
      // 确保每个题库都有正确的结构
      questionBanks.value = parsedBanks.map((bank: any) => ({
        id: bank.id,
        name: bank.name,
        questionCount: bank.questionCount || (bank.questions ? bank.questions.length : 0),
        createdAt: bank.createdAt,
        questions: bank.questions || []
      }));
      
      total.value = questionBanks.value.length;
    } else {
      questionBanks.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取题库列表失败:', error);
    ElMessage.error('获取题库列表失败');
  } finally {
    loading.value = false;
  }
};

// 事件处理函数
const handleSearch = () => {
  currentPage.value = 1;
  fetchQuestionBanks();
};

const handleEdit = (row: Bank) => {
  // 从本地存储获取完整的题库数据
  const storedBanks = localStorage.getItem('questionBanks');
  if (!storedBanks) {
    ElMessage.error('未找到题库数据');
    return;
  }

  try {
    const banks = JSON.parse(storedBanks);
    const fullBank = banks.find((bank: any) => bank.id === row.id);
    
    if (!fullBank || !fullBank.questions || !Array.isArray(fullBank.questions)) {
      ElMessage.error('题目数据格式错误');
      return;
    }

    // 格式化题目数据
    const formattedQuestions = fullBank.questions.map((q: any, index: number) => ({
      id: q.id || `Q${index + 1}`,
      title: q.title || `题目 ${index + 1}`,
      type: q.type || 'choice',
      content: q.content || q.title || `题目 ${index + 1}`,  // 确保content字段有值
      options: Array.isArray(q.options) ? q.options : [],
      answer: q.answer || '',
      difficulty: q.difficulty || 'medium',
      analysis: q.analysis || ''
    }));

    // 跳转到预览页面
    router.push({
      path: '/main/question/preview',
      query: {
        questions: JSON.stringify(formattedQuestions),
        bankId: row.id,
        bankName: row.name
      }
    });
  } catch (error) {
    ElMessage.error('处理题库数据时出错');
  }
};

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该题库吗？', '提示', {
      type: 'warning'
    });
    
    // 从题库列表中删除
    const index = questionBanks.value.findIndex(bank => bank.id === row.id);
    if (index !== -1) {
      questionBanks.value.splice(index, 1);
      total.value = questionBanks.value.length;
      
      // 更新本地存储
      localStorage.setItem('questionBanks', JSON.stringify(questionBanks.value));
      
      ElMessage.success('删除成功');
    } else {
      ElMessage.error('题库不存在');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchQuestionBanks();
};

const showCreateDialog = () => {
  createDialogVisible.value = true;
};

const goToCreateBank = (type: string) => {
  createDialogVisible.value = false;
  if (type === 'template') {
    ElMessage.info('从模板创建功能开发中');
  } else if (type === 'import') {
    importDialogVisible.value = true;
  }
};

const handleFileChange = (file: any) => {
  const isExcel = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                 file.raw.type === 'application/vnd.ms-excel';
  const isWord = file.raw.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                file.raw.type === 'application/msword';
  
  if (!isExcel && !isWord) {
    ElMessage.error('只能上传 Excel 或 Word 文件！');
    return false;
  }
  
  const isLt10M = file.raw.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB！');
    return false;
  }
  
  importForm.value.file = file.raw;
  return true;
};

const parseDocxContent = async (file: File): Promise<any[]> => {
  try {
    const arrayBuffer = await file.arrayBuffer();
    const result = await mammoth.extractRawText({ arrayBuffer });
    const text = result.value;
    
    // 预处理文本，处理分页符和多余的换行
    const processedText = text
      .replace(/\r\n/g, '\n')  // 统一换行符
      .replace(/\n{3,}/g, '\n\n')  // 将3个以上的换行替换为2个
      .replace(/\f/g, '\n')  // 将分页符替换为换行
      .trim();
    
    // 分割文本为题目
    const questions: any[] = [];
    const lines = processedText.split('\n').map(line => line.trim()).filter(line => line);
    
    let currentQuestion: any = null;
    let currentContent: string[] = [];
    let isCollectingOptions = false;
    let isCollectingQuestion = false;
    let buffer: string[] = [];
    let lastOptionKey: string | null = null;
    let questionNumber: string | null = null;
    
    for (const line of lines) {
      // 检查是否是题目编号（支持阿拉伯数字，后面跟着顿号、点或括号）
      const numberMatch = line.match(/^(\d+)[、\.\)]\s*(.*)/);
      if (numberMatch) {
        // 如果已经有当前题目，先保存
        if (currentQuestion) {
          // 处理缓冲区中的内容
          if (buffer.length > 0) {
            if (isCollectingOptions && currentQuestion.options.length > 0 && lastOptionKey) {
              // 将缓冲区内容添加到最后一个选项
              const lastOption = currentQuestion.options[currentQuestion.options.length - 1];
              lastOption.content += '\n' + buffer.join('\n');
            } else if (isCollectingQuestion) {
              // 将缓冲区内容添加到题目内容
              currentContent.push(...buffer);
            }
            buffer = [];
          }
          
          currentQuestion.content = currentContent.join('\n').trim();
          questions.push(currentQuestion);
        }
        
        // 创建新题目
        questionNumber = numberMatch[1];
        currentQuestion = {
          id: `Q${questionNumber}`,
          title: `题目${questionNumber}`,
          type: 'choice',
          content: numberMatch[2],
          options: [],
          answer: '',
          difficulty: 'medium'
        };
        currentContent = [numberMatch[2]];
        isCollectingOptions = false;
        isCollectingQuestion = true;
        buffer = [];
        lastOptionKey = null;
      }
      // 检查是否是选项（支持英文选项标识）
      else if (line.match(/^([A-D])[、\.\)]\s*(.*)/)) {
        if (currentQuestion) {
          // 处理缓冲区中的内容
          if (buffer.length > 0) {
            if (isCollectingQuestion) {
              currentContent.push(...buffer);
            } else if (isCollectingOptions && lastOptionKey) {
              const lastOption = currentQuestion.options[currentQuestion.options.length - 1];
              lastOption.content += '\n' + buffer.join('\n');
            }
            buffer = [];
          }
          
          const optionMatch = line.match(/^([A-D])[、\.\)]\s*(.*)/);
          if (optionMatch) {
            currentQuestion.options.push({
              key: optionMatch[1],
              content: optionMatch[2]
            });
            lastOptionKey = optionMatch[1];
            isCollectingOptions = true;
            isCollectingQuestion = false;
          }
        }
      }
      // 检查是否是答案
      else if (line.match(/^答案[：:]\s*([A-D])/)) {
        if (currentQuestion) {
          // 处理缓冲区中的内容
          if (buffer.length > 0) {
            if (isCollectingOptions && lastOptionKey) {
              const lastOption = currentQuestion.options[currentQuestion.options.length - 1];
              lastOption.content += '\n' + buffer.join('\n');
            } else if (isCollectingQuestion) {
              currentContent.push(...buffer);
            }
            buffer = [];
          }
          
          const answerMatch = line.match(/^答案[：:]\s*([A-D])/);
          if (answerMatch) {
            currentQuestion.answer = answerMatch[1];
            isCollectingOptions = false;
            isCollectingQuestion = false;
            lastOptionKey = null;
          }
        }
      }
      // 检查是否是同一题目的继续内容（如果当前行不是选项或答案，且正在收集题目内容）
      else if (isCollectingQuestion && currentQuestion) {
        // 检查下一行是否是选项或答案
        const nextLineIndex = lines.indexOf(line) + 1;
        const nextLine = nextLineIndex < lines.length ? lines[nextLineIndex] : '';
        const isNextLineOption = nextLine.match(/^([A-D])[、\.\)]\s*(.*)/);
        const isNextLineAnswer = nextLine.match(/^答案[：:]\s*([A-D])/);
        
        if (!isNextLineOption && !isNextLineAnswer) {
          // 如果下一行不是选项或答案，则当前行是题目内容的继续
          currentContent.push(line);
        } else {
          buffer.push(line);
        }
      }
      // 其他内容先存入缓冲区
      else {
        buffer.push(line);
      }
    }
    
    // 处理最后一个题目
    if (currentQuestion) {
      // 处理缓冲区中的内容
      if (buffer.length > 0) {
        if (isCollectingOptions && lastOptionKey) {
          const lastOption = currentQuestion.options[currentQuestion.options.length - 1];
          lastOption.content += '\n' + buffer.join('\n');
        } else if (isCollectingQuestion) {
          currentContent.push(...buffer);
        }
      }
      
      currentQuestion.content = currentContent.join('\n').trim();
      questions.push(currentQuestion);
    }
    
    // 验证题目完整性
    const validQuestions = questions.filter(q => 
      q.id && 
      q.title && 
      q.content && 
      q.options.length >= 2 && 
      q.answer
    );
    
    if (validQuestions.length === 0) {
      throw new Error('未找到有效的题目，请检查文件格式是否正确');
    }
    
    console.log('解析到的题目:', validQuestions);
    return validQuestions;
  } catch (error) {
    console.error('解析文件失败:', error);
    throw new Error('文件解析失败，请检查文件格式是否正确。支持的格式：\n1. 题目编号（如：1、2、3）\n2. 选项（如：A、B、C、D）\n3. 答案（如：答案：A）');
  }
};

const handleImport = async () => {
  if (!importForm.value.name) {
    ElMessage.warning('请输入题库名称');
    return;
  }
  
  if (!importForm.value.file) {
    ElMessage.warning('请选择要导入的文件');
    return;
  }

  importLoading.value = true;
  try {
    // 解析文件内容
    const questions = await parseDocxContent(importForm.value.file);
    
    // 创建新的题库对象
    const newBank = {
      id: `QB${String(questionBanks.value.length + 1).padStart(3, '0')}`,
      name: importForm.value.name,
      questionCount: questions.length,
      createdAt: new Date().toISOString(),
      questions: questions
    };
    
    // 添加到题库列表
    questionBanks.value.push(newBank);
    total.value = questionBanks.value.length;
    
    // 保存到本地存储
    localStorage.setItem('questionBanks', JSON.stringify(questionBanks.value));
    
    ElMessage.success(`成功导入 ${questions.length} 道题目`);
    importDialogVisible.value = false;
    
    // 重置表单
    importForm.value = {
      name: '',
      file: null
    };
  } catch (error: any) {
    console.error('导入失败:', error);
    ElMessage.error(error.message || '题库导入失败');
  } finally {
    importLoading.value = false;
  }
};

// 生命周期钩子
onMounted(() => {
  fetchQuestionBanks();
});

// 添加路由守卫，在返回时刷新数据
router.afterEach((to, from) => {
  if (from.path.includes('/main/question/preview') && to.path.includes('/main/question/bank')) {
    fetchQuestionBanks();
  }
});
</script>

<style scoped>
.question-bank-container {
  padding: 20px;
}

.search-add-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 20px;
}

.total-count {
  color: #606266;
}

.create-options {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
}

.option-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.option-item:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.option-item .el-icon {
  font-size: 24px;
  margin-bottom: 10px;
  color: #409eff;
}

.option-item span {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.option-item p {
  font-size: 14px;
  color: #909399;
  margin: 0;
  text-align: center;
}

.upload-demo {
  width: 100%;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 7px;
}

.el-upload-dragger {
  width: 100%;
}
</style>

